<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover" />
    <title>drag</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }

        #source,
        #process,
        #target,
        .source {
            border: solid 1px;
            height: 30px;
            width: 150px;
            text-align: center;
            line-height: 30px;
            margin-bottom: 30px;
            background-color: lightgreen;
            color: white;
            transition: all .15s ease;
            -webkit-transition: all .15s ease;
            font-size: 14px;
            font-weight: bold;
        }

        .source {
            position: relative;
            margin-bottom: 0;
        }

        #source {
            border-color: coral;
        }

        #process {
            height: 150px;
            line-height: 150px;
            border-color: lightgray;
        }

        #target {
            border-color: lightgreen;
        }
    </style>
</head>

<body onload="renderOrderListUI()">
    <div id="source" draggable="true">a元素</div>
    <div id="process">b元素</div>
    <div id="target">c元素</div>
    <h3>拖动排序</h3>
    <!-- <div class="source" draggable="true" data-index='1' data-value='元素1'>元素1</div>
    <div class="source" draggable="true" data-index='2' data-value='元素2'>元素2</div>
    <div class="source" draggable="true" data-index='3' data-value='元素3'>元素3</div>
    <div class="source" draggable="true" data-index='4' data-value='元素4'>元素4</div>
    <div class="source" draggable="true" data-index='5' data-value='元素5'>元素5</div> -->
    <script src="./lib/mobile-drag-drop.min.js"></script>
    <script src="./lib/scroll-behaviour.min.js"></script>
    <script>
        var addEvent = (function () {
            if (document.addEventListener) {
                return function (el, type, fn) {
                    if (el && el.nodeName || el === window) {
                        el.addEventListener(type, fn, false);
                    } else if (el && el.length) {
                        for (var i = 0; i < el.length; i++) {
                            addEvent(el[i], type, fn);
                        }
                    }
                };
            } else {
                return function (el, type, fn) {
                    if (el && el.nodeName || el === window) {
                        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
                    } else if (el && el.length) {
                        for (var i = 0; i < el.length; i++) {
                            addEvent(el[i], type, fn);
                        }
                    }
                };
            }
        })();



        var source = document.getElementById('source'),     // a元素
            process = document.getElementById('process'),   // b元素
            target = document.getElementById('target');     // c元素 


        source.addEventListener('dragstart', function (ev) {   // dragstart事件由a元素产生
            console.log('a元素开始被拖动.', ev);
        }, false)

        process.addEventListener('dragenter', function (ev) {  // dragenter事件由b元素产生
            console.log('a元素开始进入b元素.', ev);
        }, false)
        process.addEventListener('dragleave', function (ev) {  // dragleave事件由b元素产生
            console.log('a元素离开b元素.', ev);
        }, false)

        target.addEventListener('drop', function (ev) {        // drop事件由c元素产生
            console.log('a元素拖放到c元素了.', ev);
            ev.preventDefault();
        }, false)
        document.ondragover = function (e) { e.preventDefault(); }

        /**
         * ---------------------------拖动排序-----------------------------------------------------------------
         */
        MobileDragDrop.polyfill({
            // use this to make use of the scroll behaviour
            dragImageTranslateOverride: MobileDragDrop.scrollBehaviourDragImageTranslateOverride,
        });

        //更新排序数据
        function updateOrder() {
            var orders = document.querySelectorAll('.source');
            orderData = [];
            for (var i = 0; i < orders.length; i++) {
                orderData.push({
                    index: orders[i].dataset.index,
                    value: orders[i].dataset.value
                });
                //return;
            }
            console.log('NewOrders:', orderData);
            localStorage.setItem('orders', JSON.stringify(orderData));
            return orderData;
        }

        //渲染最新的排序
        function renderOrderListUI() {
            var initData = [
                { index: 1, value: '元素1' },
                { index: 2, value: '元素2' },
                { index: 3, value: '元素3' },
                { index: 4, value: '元素4' },
                { index: 5, value: '元素5' },
            ];
            var renderOrderData = localStorage.getItem('orders');
            if (!renderOrderData) {
                renderOrderData = initData;
            } else {
                renderOrderData = JSON.parse(renderOrderData);
            }
            console.log('get:', renderOrderData);
            var newUL = document.createElement('div');
            newUL.id = 'box';
            newUL.innerHTML = '';
            for (var i = 0; i < renderOrderData.length; i++) {
                var newLI = '<div class="source"  draggable="true" data-index="' + renderOrderData[i].index + '"  data-value="' + renderOrderData[i].value + '">' + renderOrderData[i].value + '</div>';
                newUL.innerHTML += newLI;
            }
            document.body.appendChild(newUL);

            //监听拖动排序
            listenDragOrder();
        }

        function listenDragOrder() {
            //拖动排序
            var source = document.querySelectorAll('.source'),
                dragElement = null, orderData = [];

            console.log(source);

            for (var i = 0; i < source.length; i++) {
                source[i].setAttribute('draggable', 'true');
                source[i].addEventListener('dragstart', function (ev) {
                    dragElement = this;

                    dragElement.style.opacity = '0.4';
                    dragElement.style.background = 'red';
                }, false);

                source[i].addEventListener('dragenter', function (ev) {
                    if (dragElement != this) {
                        this.parentNode.insertBefore(dragElement, this);
                    }
                }, false)

                source[i].addEventListener('dragleave', function (ev) {
                    if (i == source.length - 1) {
                        if (dragElement != this) {
                            if (this == this.parentNode.lastElementChild || this == this.parentNode.lastChild) {
                                this.parentNode.appendChild(dragElement);
                            }
                        }
                    }
                }, false)

                source[i].addEventListener('dragend', function (ev) {
                    dragElement = this;
                    dragElement.style.opacity = '1';
                    dragElement.style.background = 'lightgreen';
                    updateOrder();
                }, false);
            };

            document.ondragover = function (e) { e.preventDefault(); }
            document.ondrop = function (e) { e.preventDefault(); }

        }

        try {
            window.addEventListener('touchmove', function () {
            }, { passive: false })
        } catch (e) { }

    </script>
</body>

</html>